package com.rpa.server.servicerpaserver.expose.controller;

import cn.hutool.core.bean.BeanUtil;
import com.rpa.secure.servicerpasecure.common.constant.JwtClaimsConstant;
import com.rpa.secure.servicerpasecure.common.properties.JwtProperties;
import com.rpa.secure.servicerpasecure.common.result.Result;
import com.rpa.secure.servicerpasecure.common.util.JwtUtil;
import com.rpa.server.servicerpaserver.crawler.entity.User;
import com.rpa.server.servicerpaserver.crawler.operate.LogonOperate;
import com.rpa.server.servicerpaserver.crawler.service.UserService;

import com.rpa.server.servicerpaserver.expose.vo.UserVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @className: RegisterController
 * @author: lzt
 * @date: 2025/1/10 14:49
 * @Version: 1.0
 * @description:
 */
@RestController
@RequestMapping("/api/registers")
@Slf4j
@Tag(name = "本系统登录注册相关接口", description = "RegisterController")
public class RegisterController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private LogonOperate logonOperate;


    @PostMapping("/register")
    @Operation(summary = "注册本系统账号", description = "register")
    public Result<UserVo> register(@RequestBody User user){
        User registor =userService.register(user);
        //注册成功获取jwt令牌
        Map<String,Object> claims=new HashMap<>();
        claims.put(JwtClaimsConstant.TEACHER_ID,registor.getId());
        String token = JwtUtil.createJwt(jwtProperties.getSecretKey(), jwtProperties.getExpirationTime(), claims);
        UserVo userVo = new UserVo();
        BeanUtil.copyProperties(registor, userVo);
        userVo.setToken(token);
        return Result.success(userVo);
    }

    @PostMapping("/login")
    @Operation(summary = "登录本系统账号", description = "login")
    @Parameter(name = "user", description = "用户实体")
    public Result<UserVo> login(@RequestBody User user){
        User registor=userService.login(user);
        Map<String,Object> claims=new HashMap<>();
        claims.put(JwtClaimsConstant.TEACHER_ID,registor.getId());
        String token = JwtUtil.createJwt(jwtProperties.getSecretKey(), jwtProperties.getExpirationTime(), claims);
        UserVo userVo = new UserVo();
        BeanUtil.copyProperties(registor, userVo);
        userVo.setToken(token);
        logonOperate.logonCX(userVo.getId());
        return Result.success(userVo);
    }
}
